package ua.kharkov.knure.mikhaylov.st4.web.command;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import ua.kharkov.knure.mikhaylov.st4.db.entities.User;
import ua.kharkov.knure.mikhaylov.st4.db.entities.Valuta;
import ua.kharkov.knure.mikhaylov.st4.db.entities.Account;
import ua.kharkov.knure.mikhaylov.st4.db.enums.AccountState;
import ua.kharkov.knure.mikhaylov.st4.db.management.DBManager;
import ua.kharkov.knure.mikhaylov.st4.settings.DataStore;
import ua.kharkov.knure.mikhaylov.st4.settings.LocaleData;
import ua.kharkov.knure.mikhaylov.st4.settings.Path;

/**
 * Command - creates an account
 * 
 * @author Saint
 * 
 */
public class CreateAccountCommand extends Command {

	private static final long serialVersionUID = -3911404962703515671L;
	private static final Logger log = Logger
			.getLogger(CreateAccountCommand.class);

	@Override
	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		log.debug("Command starts");

		log.trace("Checking inserting parameters");

		Valuta valuta = DataStore.extractValuta(request.getParameter("valuta"));

		HttpSession session = request.getSession();

		User user = (User) session.getAttribute("user");

		// error handler
		String errorMessage = null;
		String forward = Path.PAGE_ERROR;

		if (valuta == null) {
			errorMessage = LocaleData.getResourceBundle().getString(
					"servlet.error.valuta.extraction");
			request.setAttribute("errorMessage", errorMessage);
			log.error("errorMessage --> " + errorMessage);
			return forward;
		}

		log.trace("Creating a new account");

		Account account = new Account();
		account.setBalance(0.);
		account.setValuta(valuta);
		account.setUser(user);
		account.setAccountState(AccountState.OPEN);
		// we dont need to set id here

		DBManager.getInstance().insertAccount(account);

		log.debug("Account saved");

		request.setAttribute("message", LocaleData.getResourceBundle()
				.getString("servlet.success.account.save"));
		request.setAttribute("next", Path.COMMAND_BROWSE_ACCOUNTS);
		forward = Path.PAGE_SUCCESS;

		log.debug("Command finished");
		return forward;
	}
}
